<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>range 聚合 | ElasticSearch 7.7 权威指南中文版</title>
	<meta name="keywords" content="ElasticSearch 权威指南中文版, elasticsearch 7, es7, 实时数据分析，实时数据检索" />
    <meta name="description" content="ElasticSearch 权威指南中文版, elasticsearch 7, es7, 实时数据分析，实时数据检索" />
    <!-- Give IE8 a fighting chance -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
	<link rel="stylesheet" type="text/css" href="../static/styles.css" />
	<script>
	var _link = 'search-aggregations-bucket-range-aggregation.html';
    </script>
</head>
<body>
<div class="main-container">
    <section id="content">
        <div class="content-wrapper">
            <section id="guide" lang="zh_cn">
                <div class="container">
                    <div class="row">
                        <div class="col-xs-12 col-sm-8 col-md-8 guide-section">
                            <div style="color:gray; word-break: break-all; font-size:12px;">原英文版地址: <a href="https://www.elastic.co/guide/en/elasticsearch/reference/7.7/search-aggregations-bucket-range-aggregation.html" rel="nofollow" target="_blank">https://www.elastic.co/guide/en/elasticsearch/reference/7.7/search-aggregations-bucket-range-aggregation.html</a>, 原文档版权归 www.elastic.co 所有<br/>本地英文版地址: <a href="../en/search-aggregations-bucket-range-aggregation.html" rel="nofollow" target="_blank">../en/search-aggregations-bucket-range-aggregation.html</a></div>
                        <!-- start body -->
                  <div class="page_header">
<strong>重要</strong>: 此版本不会发布额外的bug修复或文档更新。最新信息请参考 <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html" rel="nofollow">当前版本文档</a>。
</div>
<div id="content">
<div class="breadcrumbs">
<span class="breadcrumb-link"><a href="index.html">Elasticsearch 权威指南 [7.7]</a></span>
»
<span class="breadcrumb-link"><a href="search-aggregations.html">聚合</a></span>
»
<span class="breadcrumb-link"><a href="search-aggregations-bucket.html">桶(bucket)聚合</a></span>
»
<span class="breadcrumb-node">range 聚合</span>
</div>
<div class="navheader">
<span class="prev">
<a href="search-aggregations-bucket-parent-aggregation.html">« parent 聚合</a>
</span>
<span class="next">
<a href="search-aggregations-bucket-rare-terms-aggregation.html">rare_terms 聚合 »</a>
</span>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h2 class="title">
<a id="search-aggregations-bucket-range-aggregation"></a>范围(range)聚合
</h2>
</div></div></div>
<p>
一个基于值源的多桶聚合，使用户能够定义一组范围，每个范围代表一个桶。

在聚合过程中，将根据每个桶的范围检查从每个文档中提取的值，并将相关/匹配的文档“分桶”。

请注意，此聚合包括每个范围的<code class="literal">from</code>值，但不包括<code class="literal">to</code>值。
</p>
<p>示例：</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "price_ranges" : {
            "range" : {
                "field" : "price",
                "ranges" : [
                    { "to" : 100.0 },
                    { "from" : 100.0, "to" : 200.0 },
                    { "from" : 200.0 }
                ]
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/493.console"></div>
<p>响应：</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
    ...
    "aggregations": {
        "price_ranges" : {
            "buckets": [
                {
                    "key": "*-100.0",
                    "to": 100.0,
                    "doc_count": 2
                },
                {
                    "key": "100.0-200.0",
                    "from": 100.0,
                    "to": 200.0,
                    "doc_count": 2
                },
                {
                    "key": "200.0-*",
                    "from": 200.0,
                    "doc_count": 3
                }
            ]
        }
    }
}</pre>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_keyed_response_7"></a>keyed 响应
</h3>
</div></div></div>
<p>将<code class="literal">keyed</code>标志设置为<code class="literal">true</code>会将唯一的字符串键与每个桶相关联，并将范围作为哈希而不是数组返回：</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "price_ranges" : {
            "range" : {
                "field" : "price",
                "keyed" : true,
                "ranges" : [
                    { "to" : 100 },
                    { "from" : 100, "to" : 200 },
                    { "from" : 200 }
                ]
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/494.console"></div>
<p>响应：</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
    ...
    "aggregations": {
        "price_ranges" : {
            "buckets": {
                "*-100.0": {
                    "to": 100.0,
                    "doc_count": 2
                },
                "100.0-200.0": {
                    "from": 100.0,
                    "to": 200.0,
                    "doc_count": 2
                },
                "200.0-*": {
                    "from": 200.0,
                    "doc_count": 3
                }
            }
        }
    }
}</pre>
</div>
<p>也可以为每个范围自定义一个键：</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "price_ranges" : {
            "range" : {
                "field" : "price",
                "keyed" : true,
                "ranges" : [
                    { "key" : "cheap", "to" : 100 },
                    { "key" : "average", "from" : 100, "to" : 200 },
                    { "key" : "expensive", "from" : 200 }
                ]
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/495.console"></div>
<p>响应：</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
    ...
    "aggregations": {
        "price_ranges" : {
            "buckets": {
                "cheap": {
                    "to": 100.0,
                    "doc_count": 2
                },
                "average": {
                    "from": 100.0,
                    "to": 200.0,
                    "doc_count": 2
                },
                "expensive": {
                    "from": 200.0,
                    "doc_count": 3
                }
            }
        }
    }
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_script_15"></a>脚本
</h3>
</div></div></div>
<p>
range 聚合接受<code class="literal">script</code>参数。

此参数允许定义一个内联的（<code class="literal">inline</code>）脚本（<code class="literal">script</code>），它将在聚合执行期间被执行。
</p>
<p>下面这个示例显示了如何使用无痛（<code class="literal">painless</code>）脚本语言和无脚本参数的内联（<code class="literal">inline</code>）脚本：</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "price_ranges" : {
            "range" : {
                "script" : {
                    "lang": "painless",
                    "source": "doc['price'].value"
                },
                "ranges" : [
                    { "to" : 100 },
                    { "from" : 100, "to" : 200 },
                    { "from" : 200 }
                ]
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/496.console"></div>
<p>也可以使用存储(的)脚本。下面是一个简单的使用存储脚本的示例：</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">POST /_scripts/convert_currency
{
  "script": {
    "lang": "painless",
    "source": "doc[params.field].value * params.conversion_rate"
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/497.console"></div>
<p>这个新的存储脚本可以用于 range 聚合，如下所示：</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "price_ranges" : {
            "range" : {
                "script" : {
                    "id": "convert_currency", <a id="CO235-1"></a><i class="conum" data-value="1"></i>
                    "params": { <a id="CO235-2"></a><i class="conum" data-value="2"></i>
                        "field": "price",
                        "conversion_rate": 0.835526591
                    }
                },
                "ranges" : [
                    { "from" : 0, "to" : 100 },
                    { "from" : 100 }
                ]
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/498.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO235-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>存储脚本的id</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO235-2"><i class="conum" data-value="2"></i></a></p>
</td>
<td align="left" valign="top">
<p>执行存储脚本时使用的参数</p>
</td>
</tr>
</table>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_value_script_8"></a>值脚本(value script)
</h3>
</div></div></div>
<p>
假设产品价格以美元(USD)计算，但我们希望得到以欧元(EURO)计算的价格范围。

我们可以使用值脚本在聚合之前转换价格(假设转换率为0.8)。
</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /sales/_search
{
    "aggs" : {
        "price_ranges" : {
            "range" : {
                "field" : "price",
                "script" : {
                    "source": "_value * params.conversion_rate",
                    "params" : {
                        "conversion_rate" : 0.8
                    }
                },
                "ranges" : [
                    { "to" : 35 },
                    { "from" : 35, "to" : 70 },
                    { "from" : 70 }
                ]
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/499.console"></div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="_sub_aggregations_2"></a>子聚合
</h3>
</div></div></div>
<p>下面这个例子不仅将文档“分桶”到不同的桶中，还计算每个价格范围内的价格统计数据。</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "price_ranges" : {
            "range" : {
                "field" : "price",
                "ranges" : [
                    { "to" : 100 },
                    { "from" : 100, "to" : 200 },
                    { "from" : 200 }
                ]
            },
            "aggs" : {
                "price_stats" : {
                    "stats" : { "field" : "price" }
                }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/500.console"></div>
<p>响应：</p>
<div class="pre_wrapper lang-console-result">
<pre class="programlisting prettyprint lang-console-result">{
  ...
  "aggregations": {
    "price_ranges": {
      "buckets": [
        {
          "key": "*-100.0",
          "to": 100.0,
          "doc_count": 2,
          "price_stats": {
            "count": 2,
            "min": 10.0,
            "max": 50.0,
            "avg": 30.0,
            "sum": 60.0
          }
        },
        {
          "key": "100.0-200.0",
          "from": 100.0,
          "to": 200.0,
          "doc_count": 2,
          "price_stats": {
            "count": 2,
            "min": 150.0,
            "max": 175.0,
            "avg": 162.5,
            "sum": 325.0
          }
        },
        {
          "key": "200.0-*",
          "from": 200.0,
          "doc_count": 3,
          "price_stats": {
            "count": 3,
            "min": 200.0,
            "max": 200.0,
            "avg": 200.0,
            "sum": 600.0
          }
        }
      ]
    }
  }
}</pre>
</div>
<p>
如果子聚合也基于与 range 聚合相同的值源(如上面示例中的<code class="literal">stats</code>聚合)，则可以省略其值源的定义。

下面这个例子将返回与上面相同的响应：
</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "aggs" : {
        "price_ranges" : {
            "range" : {
                "field" : "price",
                "ranges" : [
                    { "to" : 100 },
                    { "from" : 100, "to" : 200 },
                    { "from" : 200 }
                ]
            },
            "aggs" : {
                "price_stats" : {
                    "stats" : {} <a id="CO236-1"></a><i class="conum" data-value="1"></i>
                }
            }
        }
    }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/501.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO236-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>不需要指定 field 为<code class="literal">price</code>，因为默认情况下，会从父级的 range 聚合中“继承”</p>
</td>
</tr>
</table>
</div>
</div>

</div>
<div class="navfooter">
<span class="prev">
<a href="search-aggregations-bucket-parent-aggregation.html">« parent 聚合</a>
</span>
<span class="next">
<a href="search-aggregations-bucket-rare-terms-aggregation.html">rare_terms 聚合 »</a>
</span>
</div>
</div>

                  <!-- end body -->
                        </div>
                        <div class="col-xs-12 col-sm-4 col-md-4" id="right_col">
                        
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </section>
</div>
<script src="../static/cn.js"></script>
</body>
</html>